const canvas = document.getElementById('gameUI');
const ctx = document.getElementById('gameUI').getContext("2d");

const images = {};

function getImgae(url) {
    return images[url];
}

function loadMultiImage(list, onSuccess){
    let current = 0;
    const total = list.length;
    for(const item of list){
        loadImage(item, function(){
            current++;
            if(current === total){
                onSuccess();
            }
        })
    }
}

function loadImage(url, callback){
    const image = new Image();
    image.src = url;
    image.onload = function(){
        images[url] = image;
        callback();
    }
}

class Tool {

    static settingFillColor(...color) {
        if (color.length === 3) {
            ctx.fillStyle = `rgb(${color[0]},${color[1]},${color[2]})`;
        } else if (color.length === 4) {
            ctx.fillStyle = `rgba(${color[0]},${color[1]},${color[2]},${color[3]})`;
        } else {
            console.error("settingFillColor:number of params is not 3 or 4");
        }
    }

    static settingStrokeColor(...color) {
        if (color.length === 3) {
            ctx.strokeStyle = `rgb(${color[0]},${color[1]},${color[2]})`;
        } else if (color.length === 4) {
            ctx.strokeStyle = `rgba(${color[0]},${color[1]},${color[2]},${color[3]})`;
        } else {
            console.error("settingStrokeColor:number of params is not 3 or 4");
        }
    }
}

class AbstractRender {
    x = 0;
    y = 0;
    draw(ctx) {

    }
}

class ImageRender extends AbstractRender {
    image = null;
    draw(ctx){
        if(this.image){
            ctx.drawImage(this.image, this.x, this.y);
        }
    }
}

class GameEnigineCore {

    onStart;

    onUpdate;

    renderList = [];

    lastIterationTime = 0;

    lastAdvancedTime = 0;

    fps = 60;

    start() {
        requestAnimationFrame(this.onFrame.bind(this));
    }

    onFrame(advancedTime) {
        //clear canvas
        ctx.save();
        ctx.clearRect(0, 0, 400, 400);


        //logic literation
        const duringTime = advancedTime - this.lastAdvancedTime;
        this.lastAdvancedTime = advancedTime;
        this.lastIterationTime += duringTime;
        const frameTime = 1000 / this.fps;
        while (this.lastIterationTime >= frameTime) {
            this.lastIterationTime -= frameTime;
            this.onUpdate(advancedTime);
        }

        //render
        for (let item of this.renderList) {
            item.draw(ctx);
        }

        //go to next frame
        ctx.restore();
        requestAnimationFrame(this.onFrame.bind(this));
    }
}